﻿/**********************************************************************************************
           Project             - mLearning2
           Company             - IronOne Technologies
           Original Developer  - Dinusha Kumarasiri 
           EMail               - dinushak@IronOneTech.com
           Date                - 2010-September
           Note                - http module to handle the authentication
---------------------------------------------------------------------------------------------*/

using System;
using System.Web;
using System.Web.Security;


namespace BoardPACDAO.Auth
{
    internal static class LoginHelper
    {
        internal static void CreateAndStoreSessionToken(string userName)
        {
            //UserDAO userDao = new UserDAO();
            HttpResponse pageResponse = HttpContext.Current.Response;

            Guid sessionToken = System.Guid.NewGuid();

            HttpCookie authenticationCookie =
                pageResponse.Cookies[FormsAuthentication.FormsCookieName];
            FormsAuthenticationTicket authenticationTicket =
                FormsAuthentication.Decrypt(authenticationCookie.Value);

            FormsAuthenticationTicket newAuthenticationTicket =
                new FormsAuthenticationTicket(
                authenticationTicket.Version,
                authenticationTicket.Name,
                authenticationTicket.IssueDate,
                authenticationTicket.Expiration,
                authenticationTicket.IsPersistent,
                sessionToken.ToString(),
                authenticationTicket.CookiePath);

            MembershipUser currentUser = Membership.GetUser(userName);

            currentUser.Comment = sessionToken.ToString();
            Membership.UpdateUser(currentUser);

            pageResponse.Cookies.Remove(FormsAuthentication.FormsCookieName);

            HttpCookie newAuthenticationCookie = new HttpCookie(
                FormsAuthentication.FormsCookieName,
                FormsAuthentication.Encrypt(newAuthenticationTicket));

            newAuthenticationCookie.HttpOnly = authenticationCookie.HttpOnly;
            newAuthenticationCookie.Path = authenticationCookie.Path;
            newAuthenticationCookie.Secure = authenticationCookie.Secure;
            newAuthenticationCookie.Domain = authenticationCookie.Domain;
            newAuthenticationCookie.Expires = authenticationCookie.Expires;

            pageResponse.Cookies.Add(newAuthenticationCookie);
        }
    }
}